package com.example.downloadmvpdemo;

import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

public class DownloadUtilImpl implements MainContract.DownloadUtil {
    // Log tag
    private static final String LOG_TAG = "DownloadUtilImpl";

    // Download Progress
    private int mProgress = 0;

    // Timer
    private Timer mTimer = null;
    private int TIMER_DELAY  = 1000;
    private int TIMER_PERIOD = 1000;

    @Override
    public void startDownload(final onDownloadListener downloadListener) {
        downloadListener.onDownloadStart();
        downloadListener.onDownloadProgress(mProgress);
        if (mTimer == null) {
            mTimer = new Timer();
        }

        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (mProgress < 100) {
                    mProgress += 10;
                }
                downloadListener.onDownloadProgress(mProgress);
                if (mProgress == 100) {
                    downloadListener.onDownloadFinish();
                    mProgress = 0;
                    mTimer.cancel();
                    mTimer = null;
                }
            }
        }, TIMER_DELAY, TIMER_PERIOD);
    }

    @Override
    public void pauseDownload(onDownloadListener downloadListener) {
        DEBUG("pauseDownload: " + mProgress);
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        downloadListener.onDownloadPause(mProgress);
    }

    @Override
    public void stopDownload(onDownloadListener downloadListener) {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        mProgress = 0;
        DEBUG("stopDownload: " + mProgress);
    }

    private void DEBUG(String info) {
        Log.d(LOG_TAG, info);
    }
}
